<?php

namespace Xin\VarDumper\Webman;

use Symfony\Component\VarDumper\Caster\ReflectionCaster;
use Symfony\Component\VarDumper\Cloner\VarCloner;
use Symfony\Component\VarDumper\Dumper\HtmlDumper;
use Symfony\Component\VarDumper\VarDumper;
use Webman\Http\Request;
use Webman\Http\Response;
use Webman\MiddlewareInterface;

class VarDumperMiddleware implements MiddlewareInterface
{
    /**
     * @var Response
     */
    protected $response;

    /**
     * @param Request $request
     * @param callable $handler
     * @return Response
     */
    public function process(Request $request, callable $handler): Response
    {
        VarDumper::setHandler(function ($var) {
            if (!$this->response) {
                $this->response = new Response();
            }
            $this->response->withBody($this->response->rawBody() . self::render($var) . "\n");
        });

        $tmpResponse = $handler($request);

        if ($this->response) {
            $tmpResponse = $this->response->withBody($this->response->rawBody() . $tmpResponse->rawBody() ?: '');
            $this->response = null;
        }

        return $tmpResponse;
    }

    /**
     * @param mixed $var
     * @return string
     */
    public static function render($var): string
    {
        $cloner = new VarCloner();
        $cloner->addCasters(ReflectionCaster::UNSET_CLOSURE_FILE_INFO);
        $dumper = new HtmlDumper();

        ob_start();
        $dumper->dump($cloner->cloneVar($var));
        return (string)ob_get_clean();
    }

}
